// eslint-disable-next-line
import * as loginService from '@/api/loginApi'
// eslint-disable-next-line
import { BasicLayout, BlankLayout, PageView, RouteView } from '@/layouts'

// 前端路由表
const constantRouterComponents = {
  // 基础页面 layout 必须引入
  BasicLayout: BasicLayout,
  BlankLayout: BlankLayout,
  RouteView: RouteView,
  PageView: PageView,
  '403': () => import(/* webpackChunkName: "error" */ '@/views/exception/403'),
  '404': () => import(/* webpackChunkName: "error" */ '@/views/exception/404'),
  '500': () => import(/* webpackChunkName: "error" */ '@/views/exception/500'),

  // 你需要动态引入的页面组件
  // 控制台
  'control': () => import('@/views/dashboard/control'),
  // 活动管理
  'activity': RouteView,
  'public': () => import('@/views/activity/public'),
  'audit': () => import('@/views/activity/audit'),
  'myActivity': () => import('@/views/activity/myActivity'),
  'myAudit': () => import('@/views/activity/myAudit'),
  // 商品管理
  'goods': RouteView,
  'goodsList': () => import('@/views/goods/goodsList'),
  'goodsIssue': () => import('@/views/goods/goodsIssue'),
  // 招商管理
  'attractinvest': RouteView,
  'entering': () => import('@/views/attractinvest/entering'),
  'supervise': () => import('@/views/attractinvest/supervise'),
  'typeinManage': () => import('@/views/attractinvest/typeinManage'),
  // 首单礼金
  'firstgifts': RouteView,
  'fentering': () => import('@/views/firstgifts/fentering'),
  'goodsManage': () => import('@/views/firstgifts/goodsManage'),
  'editGoods': () => import('@/views/firstgifts/editGoods'),
  // 业绩查询
  'achievement': RouteView,
  'myAchieve': () => import('@/views/achievement/myAchieve'),
  // 小工具箱
  'widget': RouteView,
  'makeSpreadimg': () => import('@/views/widget/makeSpreadimg'),
  'referCommi': () => import('@/views/widget/referCommi'),
  'brushCoupon': () => import('@/views/widget/brushCoupon'),
  // 虚拟截图
  'virtual': RouteView,
  'screenshot': () => import('@/views/virtual/screenshot'),
  'apply': () => import('@/views/virtual/apply'),
  'coupon': () => import('@/views/virtual/coupon'),
  'backissue': () => import('@/views/virtual/backissue'),
  'vactivity': () => import('@/views/virtual/vactivity'),
  // 收款报销
  'reimbursement': RouteView,
  'offlineCollection': () => import('@/views/reimbursement/offlineCollection'),
  'collection': () => import('@/views/reimbursement/collection'),
  'finance': () => import('@/views/reimbursement/finance'),
  'newShop': () => import('@/views/reimbursement/newShop'),
  // 对接表格
  'docking': RouteView,
  'getSample': () => import('@/views/docking/getSample'),
  'tiktokOpening': () => import('@/views/docking/tiktokOpening'),
  'taoGifts': () => import('@/views/docking/taoGifts'),
  // 知识案例
  'knowledgecase': RouteView,
  'knowindex': () => import('@/views/knowledgecase/index'),
  'kbase': () => import('@/views/knowledgecase/kbase'),
  'questionList': () => import('@/views/knowledgecase/questionList'),
  'questionDetails': () => import('@/views/knowledgecase/questionDetails'),
  // 招商案例
  'case': RouteView,
  'caseList': () => import('@/views/case/caseList'),
  'caseInfo': () => import('@/views/case/caseInfo'),
  'addCase': () => import('@/views/case/addCase'),
  // 榜单排行
  'ranklist': RouteView,
  'wangwangList': () => import('@/views/ranklist/wangwangList'),
  'groupRank': () => import('@/views/ranklist/groupRank'),
  'darkHorse': () => import('@/views/ranklist/darkHorse'),
  // 小组管理
  'teammanage': RouteView,
  'headline': () => import('@/views/teammanage/headline'),
  'ordered': () => import('@/views/teammanage/ordered'),
  'passGoods': () => import('@/views/teammanage/passGoods'),
  'issueResults': () => import('@/views/teammanage/issueResults'),
  'crewActivity': () => import('@/views/teammanage/crewActivity'),
  'dimission': () => import('@/views/teammanage/dimission'),
  'crewDoffset': () => import('@/views/teammanage/crewDoffset'),
  // 小组管理
  'helpcenter': RouteView,
  'article': () => import('@/views/helpcenter/article'),
  'articleManage': () => import('@/views/helpcenter/articleManage'),
  'pubArticle': () => import('@/views/helpcenter/pubArticle'),
  'periphery': () => import('@/views/helpcenter/periphery'),
  'toolManage': () => import('@/views/helpcenter/toolManage'),
  // 个人中心
  'mycenter': RouteView,
  'message': () => import('@/views/mycenter/message'),
  'informMange': () => import('@/views/mycenter/informMange'),
  'mySetting': () => import('@/views/mycenter/mySetting'),
  // 权限设置
  'permission': RouteView,
  'authorization': () => import('@/views/permission/authorization')
}
// 前端未找到页面路由（固定不用改）
const notFoundRouter = {
  path: '*', redirect: '/404', hidden: true
}

// 根级菜单
const rootRouter = {
  key: '',
  name: 'index',
  path: '',
  component: 'BasicLayout',
  redirect: '/dashboard',
  meta: {
    title: '首页'
  },
  children: []
}

/**
 * 动态生成菜单
 * @param token
 * @returns {Promise<Router>}
 */
export const generatorDynamicRouter = (token) => {
  return new Promise((resolve, reject) => {
    // const arr = [
    //   {
    //     rt_code: 'control',
    //     rt_id: 1,
    //     rt_name: '员工控制台',
    //     rt_parent_id: null
    //   },
    //   {
    //     rt_code: 'activity',
    //     rt_id: 2,
    //     rt_name: '活动管理',
    //     rt_parent_id: null
    //   },
    //   {
    //     rt_code: 'public',
    //     rt_id: 3,
    //     rt_name: '共用活动',
    //     rt_parent_id: 2
    //   }
    //
    // ]
    // console.log(arr)
    // // {
    // //   path: '/helpcenter',
    // //   name: 'helpcenter',
    // //   redirect: '/helpcenter/dimission',
    // //   component: RouteView,
    // //   meta: { title: '帮助中心', keepAlive: false, icon: 'smile', permission: ['*'] },
    // //   children: [
    // //     {
    // //       path: '/helpcenter/articleManage',
    // //       name: 'articleManage',
    // //       hideChildrenInMenu: true,
    // //       component: () => import('@/views/helpcenter/articleManage'),
    // //       meta: { title: '文章管理', icon: 'smile', hideHeader: true, keepAlive: false, permission: ['*'] },
    // //       children: [
    // //         {
    // //           path: '/helpcenter/articleManage/pubArticle',
    // //           name: 'pubArticle',
    // //           component: () => import('@/views/helpcenter/pubArticle'),
    // //           meta: { title: '发布文章', icon: 'smile', hidden: true, keepAlive: false, permission: ['*'] }
    // //         }]
    // //     }
    // //   ]
    // // }
    // const routerlist = []
    // // 筛选出根目录
    // for (let i = 0; i < arr.length; i++) {
    //   if (arr[i].rt_parent_id === null) {
    //     const rootobj = {
    //       path: '/' + arr[i].rt_code,
    //       name: arr[i].rt_code,
    //       hideChildrenInMenu: false,
    //       component: 'RouteView',
    //       meta: { title: arr[i].rt_name, keepAlive: false, icon: 'smile', permission: [arr[i].rt_code] },
    //       children: []
    //     }
    //     routerlist.push(rootobj)
    //   }
    // }
    // // 筛选出子目录
    // for (let i = 0; i < arr.length; i++) {
    //   if (arr[i].rt_parent_id !== null) {
    //     let parentobj = {}
    //     for (let j = 0; j < arr.length; j++) {
    //       if (arr[i].rt_parent_id === arr[j].rt_parent_id) {
    //         parentobj = arr[j]
    //       }
    //     }
    //     const childobj = {
    //       path: '/' + parentobj.rt_code + '/' + arr[i].rt_code,
    //       name: arr[i].rt_code,
    //       hideChildrenInMenu: false,
    //       component: 'RouteView',
    //       meta: { title: arr[i].rt_name, keepAlive: false, icon: 'smile', permission: [arr[i].rt_code] },
    //       children: []
    //     }
    //     routerlist.push(rootobj)
    //   }
    // }
    // console.log(rootobj)
    loginService.getCurrentUserNav(token).then(res => {
      console.log('res', res)
      const { result } = res
      const menuNav = []
      const childrenNav = []
      //      后端数据, 根级树数组,  根级 PID
      listToTree(result, childrenNav, 0)
      rootRouter.children = childrenNav
      menuNav.push(rootRouter)
      console.log('menuNav', menuNav)
      const routers = generator(menuNav)
      routers.push(notFoundRouter)
      console.log('routers', routers)
      resolve(routers)
    }).catch(err => {
      reject(err)
    })
  })
}

/**
 * 格式化树形结构数据 生成 vue-router 层级路由表
 *
 * @param routerMap
 * @param parent
 * @returns {*}
 */
export const generator = (routerMap, parent) => {
  return routerMap.map(item => {
    const { title, show, hideChildren, hiddenHeaderContent, target, icon } = item.meta || {}
    const currentRouter = {
      // 如果路由设置了 path，则作为默认 path，否则 路由地址 动态拼接生成如 /dashboard/workplace
      path: item.path || `${parent && parent.path || ''}/${item.rt_code}`,
      // 路由名称，建议唯一
      name: item.rt_code,
      // 该路由对应页面的 组件 :方案1
      // component: constantRouterComponents[item.component || item.rt_code],
      // 该路由对应页面的 组件 :方案2 (动态加载)
      component: (constantRouterComponents[item.component || item.rt_code]) || (() => import(`@/views/${item.component}`)),

      // meta: 页面标题, 菜单图标, 页面权限(供指令权限用，可去掉)
      meta: {
        title: title,
        icon: icon || undefined,
        hiddenHeaderContent: hiddenHeaderContent,
        target: target,
        permission: item.rt_code
      }
    }
    // 是否设置了隐藏菜单
    if (show === false) {
      currentRouter.hidden = true
    }
    // 是否设置了隐藏子菜单
    if (hideChildren) {
      currentRouter.hideChildrenInMenu = true
    }
    // 为了防止出现后端返回结果不规范，处理有可能出现拼接出两个 反斜杠
    if (!currentRouter.path.startsWith('http')) {
      currentRouter.path = currentRouter.path.replace('//', '/')
    }
    // 重定向
    item.redirect && (currentRouter.redirect = item.redirect)
    // 是否有子菜单，并递归处理
    if (item.children && item.children.length > 0) {
      // Recursion
      currentRouter.children = generator(item.children, currentRouter)
    }
    console.log('拼接路由', currentRouter)
    return currentRouter
  })
}

/**
 * 数组转树形结构
 * @param list 源数组
 * @param tree 树
 * @param parentId 父ID
 */
const listToTree = (list, tree, parentId) => {
  list.forEach(item => {
    // 判断是否为父级菜单
    if (item.rt_parent_id === parentId) {
      const child = {
        ...item,
        key: item.rt_code,
        children: []
      }
      // 迭代 list， 找到当前菜单相符合的所有子菜单
      listToTree(list, child.children, item.rt_parent_id)
      // 删掉不存在 children 值的属性
      if (child.children.length <= 0) {
        delete child.children
      }
      // 加入到树中
      tree.push(child)
    }
  })
}
